package com.mytinyRPC.framework;/*
package com.mytinyrpc.framework;





import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

*/
/***
 * @Author HP
 * @Description //临时类
 * @Name
 * @Param
 * @return
 **//*

public class LoadBalance {
    //集群权值之和
    private static volatile Integer smoothtotal=0;
    private static ServiceDiscovery serviceDiscovery=new ZkServiceDiscovery();
    //保存当前权重用于平滑加权随机算法
    private static HashMap<String,HashMap<URL,Integer>> curWeights=new HashMap<>();

    */
/***
     * @Author HP
     * @Description //负载均衡获取URL
     * @Name loadBalance
     * @Param [interfaceName]
     * @return framework.URL
     **//*

    public static synchronized URL loadBalance(String interfaceName ){
        if (!curWeights.containsKey(interfaceName)){
            curWeights.put(interfaceName,new HashMap<URL,Integer>());
        }
        //List<URL> urlList= RemoteMapRegister.getURL(interfaceName);
        List<URL> urlList=serviceDiscovery.getURL(interfaceName);
        for (URL url:urlList){
            if (!curWeights.get(interfaceName).containsKey(url)){
                curWeights.get(interfaceName).put(url,0);
            }
        }
        //return random(urlList);
        return SmoothWeightedRandom(urlList,interfaceName);
    }

    */
/***
     * @Author HP
     * @Description //随机算法
     * @Name random
     * @return framework.URL
     **//*

    private static URL random(List<URL> list){
        Random random = new Random();
        int i = random.nextInt(list.size());
        return list.get(i);
    }
    */
/***
     * @Author HP
     * @Description //平滑加权随机算法
     * @Name SmoothWeightedRandom
     * @Param [list]
     * @return framework.URL
     **//*

    private static URL SmoothWeightedRandom(List<URL> list,String interfaceName){
        if (list.size()<=0){
            return null;
        }
        HashMap<URL,Integer> weights=curWeights.get(interfaceName);
        //计算权值之和
        smoothtotal=0;
        for (int i = 0; i <list.size() ; i++) {
            smoothtotal+=list.get(i).getWeight();
        }
        //取当前权值最大的URL
        Collections.sort(list,(URL a,URL b)->(weights.get(b)-weights.get(a)));
        //选中的URL的当前权值减去smoothtotal
        URL result=list.get(0);
        int afterweight=weights.get(result)-smoothtotal;
        weights.replace(list.get(0),afterweight);
        //URL当前权值加上固定权值
        for (int i = 0; i <list.size() ; i++) {
            weights.replace(list.get(i),weights.get(list.get(i))+list.get(i).getWeight());
        }
        System.out.println("负载服务器："+result.toString());
        return result;
    }
}
*/
